<template>
  <!-- form 查询表单 -->
  <el-form label-width="auto" label-position="right" style="padding-bottom: 10px;"
           ref="ruleFormRef"
           :model="user"
  >
    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item label="用户名" prop="yhm">
          <el-input v-model="user.yhm" placeholder="用户名" clearable/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="用户昵称" prop="nc">
          <el-input v-model="user.nc" placeholder="用户昵称"  clearable/>
        </el-form-item>
      </el-col>
        <el-col :span="6">
          <el-form-item label="手机号" prop="sjh">
            <el-input v-model="user.phone" placeholder="手机号" clearable/>
          </el-form-item>
        </el-col>
      <el-col :span="6">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="user.email" placeholder="邮箱" clearable/>
        </el-form-item>
      </el-col>

    </el-row>
    <el-row :gutter="20">
      <el-col :span="6">
        <el-form-item label="性别" prop="sex">
          <el-select v-model="user.sex" placeholder="性别" clearable>
            <el-option label="男" value="男"/>
            <el-option label="女" value="女"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
<!--        <el-form-item label="注册时间" prop="zcsj">-->
<!--          <el-date-picker clearable style="width: 100%"-->
<!--                          type="date"-->
<!--                          v-model="user.zcsj"-->
<!--                          placeholder="注册时间"-->
<!--          />-->
          <!-- 查询表单 -->

            <el-form-item label="注册时间" prop="zcsj">
              <el-date-picker
                  v-model="user.zcsj"
                  type="date"
                  placeholder="选择日期"
              style="width: 100%"
              />
            </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="ip地址" prop="ip">
          <el-input v-model="user.ip" placeholder="ip地址" clearable/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-button type="primary" @click="doList">查询</el-button>
        <el-button type="default" @click="doFormReset">重置</el-button>
        <el-button type="success" @click="showAddDialog">新增</el-button>
      </el-col>
    </el-row>
  </el-form>

  <!-- table 数据表格 -->
  <el-table :data="tableData" :header-cell-style="{backgroundColor:'#F4F7FA',color:'gray'}" stripe show-overflow-tooltip>
    <el-table-column type="index" label="序号" width="80"/>
    <el-table-column prop="yhm" label="用户名" sortable min-width="100"/>
    <el-table-column prop="nc" label="用户昵称"/>

    <el-table-column prop="phone" label="手机号" sortable/>
    <el-table-column prop="email" label="邮箱" min-width="100"/>
    <el-table-column prop="sex" label="性别"/>
    <el-table-column label="头像">
      <template #default="scope">
        <img :src="'/img' + scope.row.tx" alt="用户头像" class="avatar" />
      </template>
    </el-table-column>
    <el-table-column prop="zcsj" label="注册时间" min-width="100"/>
    <el-table-column prop="ip" label="ip地址" min-width="100"/>
    <el-table-column label="操作" fixed="right" width="230">
      <template #default="scope">
        <el-button type="warning" @click="showUpdateDialog(scope.row)">更新</el-button>
        <el-button type="danger" @click="doDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <div style="position:fixed; bottom: 0; right: 20px; width:100%;z-index: 100">
    <el-pagination style="float:right;"
                   layout="total, sizes, prev, pager, next, jumper"
                   :page-sizes="[5, 8, 10, 20, 50]"
                   v-model:current-page="page.pageNum"
                   v-model:page-size="page.pageSize"
                   :total="page.total"
                   @change="doList"
    />
  </div>

  <!-- 新增 dialog-->
  <el-dialog v-model="addDialogVisible" title="新增用户" width="50%" top="2vh" destroy-on-close>
    <add-page ref="addPageRef"
        @flushPage="doFlushPage"
        @closeDialog="addDialogVisible = false">
    </add-page>
  </el-dialog>

  <!-- 更新 dialog-->
  <el-dialog v-model="updateDialogVisible" title="更新用户" width="40%" top="2vh" destroy-on-close>
    <update-page ref="updatePageRef"
                 @flushPage="doFlushPage"
                 @closeDialog="updateDialogVisible = false">
    </update-page>
  </el-dialog>

</template>

<script setup lang="ts">
import {nextTick, onMounted, ref} from 'vue';
import {ElMessage, FormInstance} from 'element-plus'
import axios from 'axios';
import dayjs from "dayjs";

import AddPage from './AddUserPage.vue';
import UpdatePage from './UpdateUserPage.vue';

//------------------------- form 表单 -----------------------------
// 查询条件
const user = ref({
  yhm: '',
  nc: '',
  zcsj: '',
  phone: '',
  ip: '',
  sex: '',
  email: ''
})
// 表单对象，在 <el-form> 标签上通过 ref 绑定此对象
const ruleFormRef = ref<FormInstance>()
// 表单重置
const doFormReset = () => {
  ruleFormRef.value?.resetFields()
}
// -------------------------- table 表格 ----------------------------
// 表格数据
const tableData = ref([]);
// 分页信息
const page = ref({
  pageNum: 1,     // 当前页码
  pageSize: 8,   // 每页显示的记录数
  pages: 0,       // 总页数
  total: 0        // 总记录数
})
// 分页重置
const doPageReset = () => {
  page.value.pageNum = 1;
  page.value.pageSize = 8;
  page.value.pages = 0;
  page.value.total = 0;
}

//--------------------------- CRUD ---------------------------

const doList = async () => {
  try {
    // 准备参数
    let paramsData = { ...user.value, ...page.value };
    // 特别处理日期字段
    if (paramsData.zcsj) {
      // 确保日期格式为 YYYY-MM-DD
      if (typeof paramsData.zcsj === 'string') {
        // 如果是字符串，尝试提取日期部分
        paramsData.zcsj = paramsData.zcsj.substring(0, 10);
      } else if (paramsData.zcsj instanceof Date) {
        // 如果是 Date 对象，格式化为 YYYY-MM-DD
        paramsData.zcsj = dayjs(paramsData.zcsj).format('YYYY-MM-DD');
      }
    }

    console.log('查询参数:', paramsData);
    const { data } = await axios.get('/api/user/list', { params: paramsData });
    console.log('返回数据:', data);

    if (data) {
      tableData.value = data.list || [];
      page.value.pages = data.pages || 0;
      page.value.total = data.total || 0;
    }
  } catch (error) {
    console.error('查询错误:', error);
    ElMessage.error('查询失败: ' + (error.message || '未知错误'));
  }
}



// 删除
const doDelete = async(id) => {
  const { data} = await axios.delete('/api/user/' + id);
  if (data > 0) {
    doFlushPage();		// 删除成功，查询刷新表格数据
    ElMessage.success('删除成功');
  } else {
    ElMessage.error('删除失败');
  }
}
// 刷新页面：表单重置、分页重置、重新查询
const doFlushPage = () => {
  doFormReset();
  doPageReset();
  doList();
}

//--------------------------- 页面初始化 ---------------------------
onMounted(() => {
  doList();	// 页面初始化查询显示
});

// //--------------------------- 新增 对话框 ---------------------------
const addDialogVisible = ref(false);    // 控制新增对话框的显示和隐藏(true:显示,false:隐藏)
const showAddDialog = () => {
  addDialogVisible.value = true;
}

// //--------------------------- 更新 对话框 ---------------------------
const updateDialogVisible = ref(false); // 控制更新对话框的显示和隐藏(true:显示,false:隐藏)
// 更新组件的引用, 用于调用更新页面的方法,在 <update-page> 标签上通过 ref 属性绑定该引用
const updatePageRef = ref();
const showUpdateDialog = (obj) => {
  updateDialogVisible.value = true;
  nextTick(() => {
    // 调用更新页面的方法 handleUpdateData，将数据传递给更新页面
    updatePageRef.value.handleUpdateUser(obj);
  })
}
</script>
<style scoped>
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}
</style>